package com.simon.redis;

import java.util.concurrent.TimeUnit;

import com.simon.exception.OperationFailedException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

@Component
public class RedisUtil {
	
	@Autowired
    private StringRedisTemplate redis;
	
    @Value("${jwt.expiration}")
    private Long expiration;
	
    /**
     * 设置数据到redis
     * @param key
     * @param value
     */
	public void setRedis(String key,String value) {
		try{
			//存储到redis并设置过期时间
			redis.boundValueOps(key).set(value, expiration, TimeUnit.HOURS);
		}catch (Exception ex){
			throw new OperationFailedException(ex.getMessage());
		}

	}
	
	/**
	 * 根据key获取redis的值
	 * @param key
	 * @return
	 */
	public String getRedis(String key) {
		try {
			return (String) redis.boundValueOps(key).get();
		}catch (Exception ex){
			throw new OperationFailedException(ex.getMessage());
		}
	}
	
	/**
	 * 根据key延长redis中的信息的时间
	 * @param key
	 */
	public void expireRedis(String key){
		try {
			redis.boundValueOps(key).expire(expiration, TimeUnit.HOURS);
		}catch (Exception ex){
			throw new OperationFailedException(ex.getMessage());
		}
	}
	
	/**
	 * 根据key删除redis信息
	 * @param key
	 */
	public Boolean deleteRedis(String key) {
		try {
			return redis.delete(key);
		}catch (Exception ex){
			throw new OperationFailedException(ex.getMessage());
		}
	}
	
}
